import os
from ffmpy import FFmpeg
import json


class Trans(object):

    # TODO GPU加速
    
    def __init__(self,target_path='d:/m3u8/hls'):
        self.target_path = target_path


    # 获取文件名和文件路径
    def getFileNameAndPath(self,path):
        index = path.rindex("/") #从右边开始取第一个并返回索引位置
        return path[index:],path[0:index]

    
    # 先判断是否可以直接切片，转换太慢 视频切片 输出索引和小ts文件，返回索引名和需要切片的ts路径
    def cut_ts_video(self,video_path):

        ts_name,ts_prefix_path = self.getFileNameAndPath(video_path)

        m3u8_path = self.target_path+ts_name[0:-4]+ts_name[0:-4]+".m3u8" # 输出m3u8文件
        cut_m3u8_path= self.target_path+ts_name[0:-4]+ts_name[0:-4]

        # 文件夹创建
        if not os.path.exists(self.target_path+ts_name[0:-4]):
            os.makedirs(self.target_path+ts_name[0:-4])

        ff = FFmpeg(
            executable='D:/Tools/ffmpeg/bin/ffmpeg.exe',
            inputs={video_path:'-hwaccel cuvid -c:v h264_cuvid'},
            outputs={None:'-f segment -segment_time 60 -segment_format mpegts -segment_list {0} -c copy -bsf:v h264_mp4toannexb -map 0 {1}-%03d.ts'.format(m3u8_path,cut_m3u8_path)}
        )
        print(ff.cmd)
        try:
            ff.run()

        except Exception as e:
            print(f'失败的文件:{video_path}')

        return video_path

    # 输出视频截图 作为封面
    def output_img(self,file_path):

        filePaths = open(file_path,'r',encoding='utf-8')
        for line_p in filePaths:
            print(line_p)
            ts_name,ts_path=self.getFileNameAndPath(line_p)
            out_path_img = self.target_path + ts_name[0:-6] + ts_name[0:-6] + '.jpg'
            input_path = line_p.replace(".m3u8", ".mp4")
            ff = FFmpeg(
                executable='D:/Tools/ffmpeg/bin/ffmpeg.exe',
                inputs={input_path:None},
                outputs={
                    out_path_img:'-y -f image2 -ss 10 -vframes 1'
                }
            )
            print(ff.cmd)
            try:
                ff.run()
            except Exception as e:
                print(f'失败的截图:{input_path}')


    # 将生成的文件ts路径记录
    def write_path(self,ts_path):
        with open('d:/m3u8/videoData.txt','a',encoding='utf-8') as f:
            f.write(ts_path.replace('.mp4','.m3u8')+'\n')

    # 根据生成的ts文件路径 转换出 json
    def write_relations_json(self,file_path):
        list_data=[]
        filePaths=open(file_path,'r',encoding='utf-8')
        for line in filePaths:
            print(line)
            ts_name,ts_prefix_path = self.getFileNameAndPath(line.strip('\n'))
            print(f'ts_name:{ts_name}')
            data = {
              'videoName': ts_name[1:-5],
              'videoPath': ts_name[0:-5]+ts_name,
              'videoImg': ts_name[0:-5]+ts_name.replace('m3u8', 'jpg')
            }
            print(data)
            list_data.append(data)

        content = json.dumps(list_data,ensure_ascii=False)
        fb = open('d:/m3u8/videoData.json','a',encoding='utf-8')
        fb.write(content+'\n')
        fb.close()

    # 可以换递归获取文件
    def find_all_file(self,path):
        for root ,ds ,fs in os.walk(path):
            # for d in ds:
            #     print(d)
            for f in fs:
                if f.endswith('.mp4'):
                    fullname = os.path.join(root,f)
                    print(fullname)
                    yield fullname.replace('\\', '/')



if __name__ == '__main__':

    trans = Trans()



    # for path in trans.find_all_file('F:/'):
    #     new_video_path = trans.cut_ts_video(path)
    #     trans.write_path(new_video_path)

    # trans.output_img('D:/m3u8/videoData.txt')
    trans.write_relations_json('D:/m3u8/videoData.txt')

